package it.apiconsulting.wot.controller;


import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.classic.Session;

import it.apiconsulting.wot.model.Food;
import it.apiconsulting.wot.util.HibernateUtil;


public class FoodManager extends HibernateUtil {
	
	public Food add(Food food) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(food);
		session.getTransaction().commit();
		return food;
	}
	
	public Food delete(Long id) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Food food = (Food) session.load(Food.class, id);
		if(null != food) {
			session.delete(food);
		}
		session.getTransaction().commit();
		return food;
	}

	public Food getFoodById(Long idFood) {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Food food = null;
		try {
			
			Query query = session.createQuery("FROM Food WHERE id = "+idFood);
			food = (Food)query.uniqueResult();
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return food;
	}

	public List<Food> list() {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Food> foods = null;
		try {
			
			Query query = session.createQuery("from Food");
			foods = (List<Food>)query.list();
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return foods;
	}
}
